# Docker部署脚本 (PowerShell版本)
param(
    [string]$Environment = "dev",
    [string]$ComposeFile = "",
    [string]$Tag = "latest",
    [switch]$Help
)

# 颜色定义
$Red = "Red"
$Green = "Green"
$Yellow = "Yellow"

# 打印带颜色的消息
function Write-Info {
    param([string]$Message)
    Write-Host "[INFO] $Message" -ForegroundColor $Green
}

function Write-Warning {
    param([string]$Message)
    Write-Host "[WARNING] $Message" -ForegroundColor $Yellow
}

function Write-Error {
    param([string]$Message)
    Write-Host "[ERROR] $Message" -ForegroundColor $Red
}

# 显示帮助信息
if ($Help) {
    Write-Host "用法: .\docker-deploy.ps1 [选项]"
    Write-Host "选项:"
    Write-Host "  -Environment ENV    环境 (dev|prod, 默认: dev)"
    Write-Host "  -ComposeFile FILE   compose文件 (默认: 根据环境自动选择)"
    Write-Host "  -Tag TAG           镜像标签 (默认: latest)"
    Write-Host "  -Help              显示帮助信息"
    exit 0
}

# 根据环境设置compose文件
if (-not $ComposeFile) {
    if ($Environment -eq "prod") {
        $ComposeFile = "docker-compose.prod.yml"
        Write-Info "使用生产环境配置: $ComposeFile"
    } else {
        $ComposeFile = "docker-compose.yml"
        Write-Info "使用开发环境配置: $ComposeFile"
    }
}

Write-Info "开始部署Docker服务..."
Write-Info "环境: $Environment"
Write-Info "Compose文件: $ComposeFile"
Write-Info "镜像标签: $Tag"

# 检查Docker是否运行
try {
    docker info | Out-Null
} catch {
    Write-Error "Docker未运行，请启动Docker Desktop"
    exit 1
}

# 检查compose文件是否存在
if (-not (Test-Path $ComposeFile)) {
    Write-Error "Compose文件不存在: $ComposeFile"
    exit 1
}

# 停止现有服务
Write-Info "停止现有服务..."
docker-compose -f $ComposeFile down

# 清理未使用的镜像和容器
Write-Info "清理未使用的资源..."
docker system prune -f

# 启动服务
Write-Info "启动服务..."
docker-compose -f $ComposeFile up -d

# 等待服务启动
Write-Info "等待服务启动..."
Start-Sleep -Seconds 10

# 检查服务状态
Write-Info "检查服务状态..."
docker-compose -f $ComposeFile ps

# 检查健康状态
Write-Info "检查健康状态..."
for ($i = 1; $i -le 30; $i++) {
    $Status = docker-compose -f $ComposeFile ps
    if ($Status -match "Up") {
        Write-Info "服务启动成功!"
        break
    }
    Write-Warning "等待服务启动... ($i/30)"
    Start-Sleep -Seconds 2
}

# 显示日志
Write-Info "显示服务日志..."
docker-compose -f $ComposeFile logs --tail=20

Write-Info "部署完成!"
Write-Info "访问地址: http://localhost:7001"
Write-Info "API文档: http://localhost:7001/api-docs" 